//
//  CollectionViewController.swift
//  FirstSwiftProduct
//
//  Created by 知合金服-Mini on 2017/12/12.
//  Copyright © 2017年 范泽华. All rights reserved.
//

import UIKit



class CollectionViewController: BasePushViewController ,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 5
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 5))
        return headView
    }
    func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
        return 5
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let headView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 5))
        return headView
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return cellArr.count
    }
    
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:CollectCell = tableView.dequeueReusableCell(withIdentifier: "CollectCell") as! CollectCell
//        if cell == nil {
//            cell = UITableViewCell.init(style: .default, reuseIdentifier: "cellId")
//        }
        let dict:NSDictionary = cellArr[indexPath.section] as! NSDictionary
        
        cell.connectData(dict: dict, index: String.init(format: "%ld", indexPath.section))

        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 88
    }
    
    var animationView : LoadingView!
    var table : UITableView!
    let collectArr:NSArray = NSArray.init(contentsOfFile: Bundle.main.path(forResource: "Collect", ofType: "plist")!)!
    
    var cellArr = NSMutableArray.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //searchView
        self.titleLabel.text = "收藏"
        
        let searchView = UISearchBar.init(frame: CGRect(x: 0, y: CGFloat(kStatus_Navigation_height), width: SCREEN_WIDTH, height: 40))
        searchView.barStyle = .default
        searchView.showsCancelButton = true
        view.addSubview(searchView)
        searchView.placeholder = "搜索"
        searchView.delegate = self
        searchView.setValue("取消", forKeyPath: "cancelButton.title")
        //        let uiButton = searchView.value(forKey: "cancelButton") as! UIButton
//        uiButton.setTitle("取消", for: .normal)
        
//        animationView = LoadingView.init(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCRENN_HEIGHT - 50))
//        view.addSubview(animationView)
//        animationView.active()
//
        
        table = UITableView.init(frame: CGRect(x: 0, y: CGFloat(kStatus_Navigation_height) + 40, width: SCREEN_WIDTH, height: SCRENN_HEIGHT - (CGFloat(kStatus_Navigation_height) + 40)), style: .grouped)
        table.delegate = self
        table.dataSource = self
        view.addSubview(table)
        table.register(UINib.init(nibName: "CollectCell", bundle: Bundle.main), forCellReuseIdentifier: "CollectCell")
        cellArr.addObjects(from: collectArr as! [Any])
//        animationView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
//        animationView.center = self.view.center
//        animationView.contentMode = .scaleAspectFill
//        
//        view.addSubview(animationView)
//        
//        animationView.loopAnimation = true
//        
//        
//        animationView.play()
        
//        searchView.addObserver(self, forKeyPath: "text", options: .new, context: nil)
//
//        table.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
    }

    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
       
        if keyPath == "text" {
            print(change as Any)
        }
        
        if keyPath == "contentOffset" {
            print(change as Any)
        }
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        print("end")
        print(searchBar.text as Any)
    }
    
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        print("begin")

    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.endEditing(true)
//        animationView.stopActive()
//        animationView.isHidden = true
        cellArr.removeAllObjects()
        
        //检索功能
        print(searchBar.text as Any)
        
        search(ssss: searchBar.text!)
        table.reloadData()
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
        if (searchBar.text?.isEmpty)! {
            searchBar.setValue("取消", forKeyPath: "cancelButton.title")
        }else{
            searchBar.setValue("搜索", forKeyPath: "cancelButton.title")
        }

    }
    
    func search(ssss:String)  {
        
        for i in 0...(collectArr.count - 1) {
            let dict:NSDictionary = collectArr[i] as! NSDictionary
            let strr = dict["title"] as? NSString
            
            if strr?.range(of: ssss).location != NSNotFound {
                print(i,strr as Any)
                cellArr.add(dict)
            }else{
                print(i,"nononononononononononononono")
            }
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        
        let  titlebutton:String = searchBar.value(forKeyPath: "cancelButton.title") as! String
        searchBar.endEditing(true)
        if titlebutton == "取消" {
            print(titlebutton as Any)
            
            cellArr.removeAllObjects()
            cellArr.addObjects(from: collectArr as! [Any])
            table.reloadData()
        }
        
        if titlebutton == "搜索" {
            search(ssss: searchBar.text!)
            table.reloadData()
        }
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
